package com.xujianlong.day04;

import com.xujianlong.bean.UserBehavior;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.api.common.typeinfo.Types;


public class Flink01_Project_PV {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);

        DataStreamSource<String> dataStreamSource = env.readTextFile("input/UserBehavior.csv");

        SingleOutputStreamOperator<Tuple2<UserBehavior, Integer>> map = dataStreamSource.map(new MapFunction<String, Tuple2<UserBehavior, Integer>>() {
            @Override
            public Tuple2<UserBehavior, Integer> map(String s) throws Exception {

                String[] fields = s.split(",");
                return Tuple2.of(new UserBehavior(
                        Long.valueOf(fields[0]),
                        Long.valueOf(fields[1]),
                        Integer.valueOf(fields[2]),
                        fields[3],
                        Long.valueOf(fields[4])), 1);
            }
        });
        SingleOutputStreamOperator<Tuple2<UserBehavior, Integer>> filter = map.filter(new FilterFunction<Tuple2<UserBehavior, Integer>>() {
            @Override
            public boolean filter(Tuple2<UserBehavior, Integer> userBehaviorIntegerTuple2) throws Exception {
                return "pv".equals(userBehaviorIntegerTuple2.f0.getBehavior());
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Long>> sum = filter.keyBy(new KeySelector<Tuple2<UserBehavior, Integer>, String>() {
            @Override
            public String getKey(Tuple2<UserBehavior, Integer> userBehaviorIntegerTuple2) throws Exception {
                return userBehaviorIntegerTuple2.f0.getBehavior();
            }
        }).map(userBehaviorToCount -> Tuple2.of(userBehaviorToCount.f0.getBehavior(), 1L)).returns(Types.TUPLE(Types.STRING, Types.LONG)).keyBy(0).sum(1);

        sum.print();

        env.execute();
    }
}
